<template>
	<div>		
		<el-button 
			:icon="icon"
			@click="load">根据最近手术记录自动计算</el-button>
		<span v-if="message">{{ message }}</span>
	</div>
</template>
<script>
	import Vue from 'vue';
	import ElementUI from 'element-ui';
	import SurgeryModel from '../js/config/surgery';
	import Service from 'winged/utils/wt-model-service';
	import FormUtils from 'winged/utils/wt-form-utils';
	import ModelUtils from 'winged/utils/wt-model-utils';
	import TimeUtils from 'winged/utils/wt-time-utils';
	import moment from 'moment';	

	Vue.use(ElementUI);

	export default {
		name: 'wt-case-image-time-calculator',
		props: {
			// 字段对象（包含字段配置信息）
			field: {
				type: Object,
				required: true,
			},
			// 表单数据对象
			form: {
				type: Object,
				required: true,
			},
			currentId: {
				type: [Object, String, Number],
				default: null
			},
			paramsData: {
				type: Object,
				default: null
			}
		},
		computed: {
			icon() {
				return this.loading ? 'loading' : 'date';
			}
		},
		data() {
			return {
				message: null,
				loading: false,
			};
		},
		methods: {
			// Loads data and calculate
			load() {
				this.loading = true;
				let _this = this;
				Service.query(SurgeryModel, this.paramsData, function(data) {
					_this.loading = false;
					_this.setQueryResult(FormUtils.parseArray(data));
				}, function(error) {
					_this.loading = false;
					console.error(error);
					_this.message = '查找手术记录失败，请重试';
				});
			},
			reset() {
				this.load();
			},
			setQueryResult(data) {
				let latestDate = null;
				let latestRecord = null;
				for (let i = 0; i < data.length; i ++) {
					let item = data[i];
					ModelUtils.normalizeData(SurgeryModel, item);
					let date = item.surgeryDate;
					if ((latestDate == null || latestDate < date) && date <= this.form.examDate) {
						latestDate = date;
						latestRecord = item;
					}
				}
				if (latestRecord) {
					this.message = '找到最近一次手术记录：' + TimeUtils.format(latestDate, 'date') + ' - ' + latestRecord.surgeryName;
					let examDate = this.form.examDate;
					let surgeryDate = moment(latestDate);
					let imageDate = moment(this.form.examDate).endOf('day');
					let years = imageDate.diff(surgeryDate, 'years');
					if (years > 0) {
						surgeryDate = surgeryDate.add(years, 'y');
					}
					let months = imageDate.diff(surgeryDate, 'months');
					if (months > 0) {
						surgeryDate = surgeryDate.add(months, 'M');
					}
					let days = imageDate.diff(surgeryDate, 'days');
					
					this.form.afterSurgeryYear = years > 0 ? years : 0;
					this.form.afterSurgeryMonth = months > 0 ? months : 0;
					this.form.afterSurgeryDay = days > 0 ? days : 0;
				}
				else {
					this.message = '当前影像日期之前没有找到手术记录';
				}
			}
		},
		mounted() {
			// 暂时不进行自动自动刷新
			// this.load();
		}
	}
</script>
<style scoped>
	div {
		margin-top: 27px;
	}
</style>